import { reactive, ref,computed } from 'vue'


import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import request from '@/base/request'
import router from '@/router'
import SaveExamParm from '@/types/saveExamParm'
export default function () {

    const saveExamParm = ref<SaveExamParm>({
        beginTime: new Date().toLocaleString(),
        validity:60,
        examProblemList:[[],[],[],[],[],[],[]],
        examScoreList:[0,1,1,1,1,1,0],
        needPeople: new Map(),
        notes:'应自觉遵守考试纪律，诚信应考，不得作弊或替考\n考试期间，不得与他人交流、传递信息或寻求帮助\n请在规定时间完成，到时自动交卷'
    })

    const score=computed(()=>{
        let sum=0;
        for(let i=1;i<6;i++){
            sum+=saveExamParm.value.examProblemList[i].length*saveExamParm.value.examScoreList[i]
        }
        return sum
    })


    const step = ref(0)

    const ruleFormRef = ref<FormInstance>()

    const rules = reactive<FormRules<SaveExamParm>>({
        examName: [
            { required: true, message: '请输入考试名', trigger: 'blur' },
            { min: 1, max: 30, message: '请在1到30字之间', trigger: 'blur' },
        ],
        validity: [
            { required: true, message: '请输入一个数字', trigger: 'blur' },
            { type: 'number', message: '请输入一个数字', trigger: ['blur', 'change'] },
            {
                validator: (rule, value, callback) => {
                    if (value <= 1 || value>10000000) {
                        callback(new Error('必须大于1小于10000000'));
                    } else {
                        callback();
                    }
                }, trigger: ['blur', 'change']
            },
        ],
        beginTime:[
            { required: true, message: '请选择时间', trigger: 'blur' },
        ]
    })





    async function saveExam() {
        saveExamParm.value.score=score.value;
        saveExamParm.value.beginTime=new Date(saveExamParm.value.beginTime).toLocaleString()
        const response= (await request.post("/problem/exam/admin/saveExam",saveExamParm.value)).data
        if(response.code===200){
            ElMessage.success("成功");
            router.push("/admin/exam")
        }else{
            ElMessage.error(`失败:${response.msg}`)
        }
    }

    async function getExamInfo(id:number) {
        const response= (await request.get(`/problem/exam/admin/getExamById/${id}`)).data
        if(response.code===200){
            saveExamParm.value=response.data
        }else{
            ElMessage.error(`获取数据失败${response.msg}`)
            router.push("/admin/exam")
        }
    }



    function handleProblemIndex(index:number,value:number){
        let t=saveExamParm.value.examProblemList[step.value][index+value]
        saveExamParm.value.examProblemList[step.value][index+value]=saveExamParm.value.examProblemList[step.value][index]
        saveExamParm.value.examProblemList[step.value][index]=t
    }


    return { saveExamParm, step,ruleFormRef, rules,score,
        getExamInfo,saveExam,handleProblemIndex
     }
}